import serial
import struct

class Port:
    def __init__(self,receive_len,port_name,baudrate=230400):
        self.port_name = port_name
        self.baudrate = baudrate
        self.receive_len = receive_len
        self.data = []
        self.receive_frame_head = bytes([0xef,0xff,0xff,0xff]) # 收帧头
        self.receive_frame_tail = bytes([0x00, 0x00, 0x80, 0x7f]) # 收帧尾

        self.frame_head = bytes([0x00, 0x00, 0x80, 0x7f])  # 发帧头
        self.frame_tail = bytes([0xef,0xff,0xff,0xff])  # 发帧尾

        try:
            self.ser = serial.Serial(self.port_name, self.baudrate, timeout=1)
        except Exception as exc:
            print(f"串口打开异常: {exc}")
        
    def send_data(self,data):

        # 将每个浮动点数转换为字节，使用 struct.pack 将其打包
        data_body = b''.join(struct.pack('f', x) for x in data)  # 'f' 格式表示浮点数

        # 在数据前后加上帧头和帧尾
        full_data = self.frame_head + data_body
        # full_data = data_body

        # 发送数据
        try:
            self.ser.write(full_data)
            # print(f"发送成功，长度: {len(full_data)} 字节")
            # print("发送数据(十六进制):", full_data.hex(' '))  # 打印发送的十六进制数据，用空格分隔
        except Exception as e:
            print(f"发送失败: {e}")
    
    def receive_data(self):
        try:
            # 读取数据
            received = self.ser.read(2*self.receive_len+8)
            
            if received:
                # print(f"接收成功，长度: {len(received)} 字节")
                # print(received.hex(),end=" ")  # 打印接收的十六进制数据，用空格分隔
                
                # 这里可以添加数据解析逻辑
                # 例如检查帧头帧尾，提取数据部分等
                if len(received) >= 2*(self.receive_len+8):  
                    for i in range(len(received)):
                        if received[i:i+4] == self.receive_frame_head:
                            head_index = i+4
                        if received[i:i+4] == self.receive_frame_tail and (head_index is not None):
                            tail_index = i
                            break
                    
                    data_body = received[head_index:tail_index]
                    # 解析浮点数数据
                    if len(data_body) % 4 == 0:  # 每个浮点数占4字节
                        floats = []
                        for i in range(0, len(data_body), 4):
                            floats.append(struct.unpack('f', data_body[i:i+4])[0])
                        print("解析出的浮点数:", floats)
                    else:
                        print("数据体长度不符合浮点数格式")
                else:
                    print("接收数据长度不足")
            else:
                print("未接收到数据")
                
            return floats
        except Exception as e:
            print(f"接收失败: {e}")
            return None
            
    def close(self):
        if self.ser and self.ser.is_open:
            self.ser.close()
            print("串口已关闭")

